package cn.iocoder.lw.module.core.controller.app.device;

import cn.iocoder.lw.framework.common.pojo.CommonResult;
import cn.iocoder.lw.framework.common.pojo.PageResult;
import cn.iocoder.lw.framework.common.util.object.BeanUtils;
import cn.iocoder.lw.module.core.controller.admin.device.vo.CoreDeviceRespVO;
import cn.iocoder.lw.module.core.controller.admin.device.vo.CoreDeviceSaveReqVO;
import cn.iocoder.lw.module.core.controller.admin.device.vo.CoreDevicePageReqVO;
import cn.iocoder.lw.module.core.service.device.CoreDeviceService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;

import static cn.iocoder.lw.framework.common.pojo.CommonResult.success;
import static cn.iocoder.lw.framework.web.core.util.WebFrameworkUtils.getLoginUserId;

@Tag(name = "用户 APP - 核心设备")
@RestController
@RequestMapping("/core/device")
@Validated
@Slf4j
public class AppCoreDeviceController {

    @Resource
    private CoreDeviceService deviceService;

    @PostMapping("/create")
    @Operation(summary = "创建设备")
    @PreAuthorize("@ss.hasPermission('core:device:create')")
    public CommonResult<Long> createDevice(@Valid @RequestBody CoreDeviceSaveReqVO createReqVO) {
        // 转换为管理后台的VO
        CoreDeviceSaveReqVO adminSaveReqVO = BeanUtils.toBean(createReqVO, CoreDeviceSaveReqVO.class);

        return success(deviceService.createDevice(adminSaveReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新设备")
    @PreAuthorize("@ss.hasPermission('core:device:update')")
    public CommonResult<Boolean> updateDevice(@Valid @RequestBody CoreDeviceSaveReqVO updateReqVO) {
        // 转换为管理后台的VO
        CoreDeviceSaveReqVO adminSaveReqVO = BeanUtils.toBean(updateReqVO, CoreDeviceSaveReqVO.class);

        deviceService.updateDevice(adminSaveReqVO);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得设备")
    @Parameters({
            @Parameter(name = "id", description = "编号", required = true, example = "1024")
    })
    @PreAuthorize("@ss.hasPermission('core:device:query')")
    public CommonResult<CoreDeviceSaveReqVO> getDevice(@RequestParam("id") Long id) {
        CoreDeviceRespVO device = deviceService.getDevice(id);
        if (device == null) {
            return success(null);
        }

        // 转换为APP的VO
        CoreDeviceSaveReqVO appDevice = BeanUtils.toBean(device, CoreDeviceSaveReqVO.class);

        // 计算质保剩余天数
        if (appDevice.getWarrantyEndTime() != null) {
            LocalDateTime now = LocalDateTime.now();
            if (appDevice.getWarrantyEndTime().isAfter(now)) {
                Long daysRemaining = ChronoUnit.DAYS.between(now, appDevice.getWarrantyEndTime());
                appDevice.setWarrantyDaysRemaining(daysRemaining.intValue());
            } else {
                appDevice.setWarrantyDaysRemaining(0);
            }
        }
        return success(appDevice);
    }


    @GetMapping("/my-page")
    @Operation(summary = "获得我负责项目的设备分页")
    @PreAuthorize("@ss.hasPermission('core:device:query')")
    public CommonResult<PageResult<CoreDeviceSaveReqVO>> getMyDevicePage(@Valid CoreDeviceSaveReqVO pageReqVO) {
        Long currentUserId = getLoginUserId();

        // 转换为管理后台的VO
        CoreDevicePageReqVO adminPageReqVO = BeanUtils.toBean(pageReqVO, CoreDevicePageReqVO.class);

        PageResult<CoreDeviceRespVO> pageResult = deviceService.getDevicePage(adminPageReqVO);
        PageResult<CoreDeviceSaveReqVO> appPageResult = BeanUtils.toBean(pageResult, CoreDeviceSaveReqVO.class);

        // 处理APP特有的字段
        appPageResult.getList().forEach(device -> {
            // 计算质保剩余天数
            if (device.getWarrantyEndTime() != null) {
                LocalDateTime now = LocalDateTime.now();
                if (device.getWarrantyEndTime().isAfter(now)) {
                    Long daysRemaining = ChronoUnit.DAYS.between(now, device.getWarrantyEndTime());
                    device.setWarrantyDaysRemaining(daysRemaining.intValue());
                } else {
                    device.setWarrantyDaysRemaining(0);
                }
            }

            // 设置为当前用户负责的项目设备
            device.setIsOwner(true);
        });

        // 只保留我负责的项目设备
        List<CoreDeviceSaveReqVO> myList = appPageResult.getList().stream()
                .filter(device -> Boolean.TRUE.equals(device.getIsOwner()))
                .toList();

        appPageResult.setList(myList);
        appPageResult.setTotal((long) myList.size());

        return success(appPageResult);
    }

    @GetMapping("/project/{projectId}")
    @Operation(summary = "根据项目编号获取设备列表")
    @Parameter(name = "projectId", description = "项目编号", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('core:device:query')")
    public CommonResult<List<CoreDeviceSaveReqVO>> getDeviceListByProjectId(@PathVariable("projectId") Long projectId) {
        List<CoreDeviceRespVO> list = deviceService.getDeviceListByProjectId(projectId);

        // 转换为APP的VO
        List<CoreDeviceSaveReqVO> appList = BeanUtils.toBean(list, CoreDeviceSaveReqVO.class);

        // 处理APP特有的字段
        appList.forEach(device -> {
            // 计算质保剩余天数
            if (device.getWarrantyEndTime() != null) {
                LocalDateTime now = LocalDateTime.now();
                if (device.getWarrantyEndTime().isAfter(now)) {
                    Long daysRemaining = ChronoUnit.DAYS.between(now, device.getWarrantyEndTime());
                    device.setWarrantyDaysRemaining(daysRemaining.intValue());
                } else {
                    device.setWarrantyDaysRemaining(0);
                }
            }

        });

        return success(appList);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除设备")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('core:device:delete')")
    public CommonResult<Boolean> deleteDevice(@RequestParam("id") Long id) {
        deviceService.deleteDevice(id);
        return success(true);
    }

}